package com.nytd.demo;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Enumeration;

@RequestMapping("/r1")
@RestController
public class UserController {

    @RequestMapping("/m1")
    public String method(String name) {
        System.out.println("接收成功");
        return "name: " + name;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute("userName", "java");
        }
        return "存储成功";
    }

    @RequestMapping("/getSession1")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        String userName = null;
        if (session != null && session.getAttribute("userName") != null) {
            userName = (String)session.getAttribute("userName");
        }
        return "userName: " + userName;
    }

    @RequestMapping("/getSession2")
    public String getSession2(@SessionAttribute(value = "userName", required = false) String userName) {
        return "userName: " + userName;
    }

    @RequestMapping("/getSession3")
    public String getSession3(HttpSession session){
        String userName = (String)session.getAttribute("userName");
        return "userName: " + userName;
    }

    @RequestMapping("/getHeader1")
    public String getHeader1(HttpServletRequest request){
        String userAgent = request.getHeader("user-Agent");
        return "userAgent: " + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("user-Agent") String userAgent){
        return "userAgent: " + userAgent;
    }
}
